import Vue from 'vue'

import VueRouter from 'vue-router'

import store from '@/store/index'

// 导入登录注册组件
// import regPage from '@/views/Reg/regPage.vue'
// import loginPage from '@/views/Login/loginPage.vue'
// import mainPage from '@/views/Main/mainPage.vue'
// import homePage from '@/views/Menus/Home/Home.vue'
// import UserInfo from '@/views/Menus/User/UserInfo.vue'
// import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
// import UserPwd from '@/views/Menus/User/UserPwd.vue'
// import ArtCate from '@/views/Menus/Article/ArtCate.vue'
// import ArtList from '@/views/Menus/Article/ArtList.vue'

// 导入 组件
const regPage = () => import('@/views/Reg/regPage.vue')
const loginPage = () => import('@/views/Login/loginPage.vue')
const mainPage = () => import('@/views/Main/mainPage.vue')
const homePage = () => import('@/views/Menus/Home/Home.vue')
const UserInfo = () => import('@/views/Menus/User/UserInfo.vue')
const UserAvatar = () => import('@/views/Menus/User/UserAvatar.vue')
const UserPwd = () => import('@/views/Menus/User/UserPwd.vue')
const ArtCate = () => import('@/views/Menus/Article/ArtCate.vue')
const ArtList = () => import('@/views/Menus/Article/ArtList.vue')

Vue.use(VueRouter)
// 声明路由规则
const routes = [
  { path: '/reg', component: regPage },
  { path: '/login', component: loginPage },
  {
    path: '/',
    component: mainPage,
    redirect: '/home',
    children: [
      { path: 'home', component: homePage },
      { path: 'user-info', component: UserInfo },
      { path: 'user-avatar', component: UserAvatar },
      { path: 'user-pwd', component: UserPwd },
      { path: 'art-cate', component: ArtCate },
      { path: 'art-list', component: ArtList }
    ]
  }
]

const router = new VueRouter({
  routes
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 没登录拦截
router.beforeEach((to, from, next) => {
  if (!store.state.user.token && to.path !== '/login' && to.path !== '/reg') {
    return next('/login')
  }
  next()
})

export default router
